package io.gitee.terralian.code.generator.controller;

import java.util.List;

import io.gitee.terralian.code.generator.dao.entity.DataBase;
import io.gitee.terralian.code.generator.dao.service.DataBaseService;
import io.gitee.terralian.code.generator.framework.entity.Result;
import io.gitee.terralian.code.generator.service.db.RemoteDBService;
import io.gitee.terralian.code.generator.service.db.entity.ColumnRef;
import io.gitee.terralian.code.generator.service.db.entity.TableRef;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("db")
@AllArgsConstructor
public class DBController {

    private final DataBaseService dataBaseService;
    private final RemoteDBService remoteDBService;

    @GetMapping("list")
    public Result<List<DataBase>> list() {
        List<DataBase> list = dataBaseService.list();
        return Result.success(list);
    }

    @GetMapping("tables")
    public Result<List<TableRef>> tables(@RequestParam("id") String id) {
        return Result.success(remoteDBService.getTables(id));
    }

    @GetMapping("columns")
    public Result<List<ColumnRef>> columns(@RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        return Result.success(remoteDBService.getColumns(id, tableName));
    }

    @PostMapping("save")
    public Result<Object> save(@RequestBody DataBase dataBase) {
        dataBaseService.save(dataBase);
        return Result.defaultSuccess();
    }

    @PostMapping("connect-test")
    public Result<String> connectTest(@RequestBody DataBase dataBase) {
        return remoteDBService.connectTest(dataBase);
    }

    @PutMapping("update")
    public Result<Object> update(@RequestBody DataBase dataBase) {
        dataBaseService.updateById(dataBase);
        return Result.defaultSuccess();
    }

    @DeleteMapping("delete")
    public Result<Object> delete(@RequestParam("id") String id) {
        dataBaseService.removeById(id);
        return Result.defaultSuccess();
    }
}
